package com.easylinkin.linkappapi.openapi.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.easylinkin.linkappapi.openapi.dto.systemDock.RaiseDustDTO;
import com.easylinkin.linkappapi.openapi.dto.systemDock.ResultDTO;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DeviceInfoPostUtil {

	private static final Logger logger = LoggerFactory.getLogger(DeviceInfoPostUtil.class);

	public static String handleData(String appid, String secret, String data, String url) {

		String nonce = nonceGen();
		data = data.replace("\"raiseDustDTO\":{", "").replace("},", ",");
		String dataStr = String.format("appid=%s&data=%s&nonce=%s&appsecret=%s", appid, data, nonce, secret);
		// 获取签名
		String sign = EncryptionUtil.getArrayToSHA256(dataStr.toLowerCase().getBytes());

		Map<String, Object> map = new HashMap<>();

		map.put("data", data);
		map.put("appid", appid);
		map.put("nonce", nonce);
		map.put("sign", sign);

		String responseStr = "";
		RaiseDustDTO device = new Gson().fromJson(data, RaiseDustDTO.class);
		try {
			logger.info("平台对接，数据接口为："+url+"推送的设备数据为:" + JSONObject.toJSONString(map));
			responseStr = HttpClientUtil.doPost(url, JSONObject.toJSONString(map));
			logger.info("推送结果为：" + responseStr);

			ResultDTO fromJson = new Gson().fromJson(responseStr, ResultDTO.class);

			if (fromJson.getCode() != 0 && StringUtils.isNotBlank(device.getDeviceName())) {
				throw new RuntimeException("设备:" + device.getDeviceName() + " 信息注册失败 " + fromJson.getMessage());
			}

		} catch (IOException e) {
			logger.error("DeviceInfoPostUtil url:{} ,error:{}", url, e.getMessage());
		}catch (Exception e){
			throw new RuntimeException(String.format("设备:" + device.getDeviceName() + " 信息注册失败 %s", e.getMessage()));
		}
		return responseStr;
	}

	public static String handleData2(String data, String url) {
		data = data.replace("\"raiseDustDTO\":{", "").replace("},", ",");
		String responseStr = "";
		RaiseDustDTO device = new Gson().fromJson(data, RaiseDustDTO.class);
		try {
			logger.info("平台对接，数据接口为："+url+"推送的设备数据为:" + data);
			responseStr = HttpClientUtil.doPost(url, data);
			logger.info("推送结果为：" + responseStr);

			ResultDTO fromJson = new Gson().fromJson(responseStr, ResultDTO.class);

			if (fromJson.getStatus() != null) {
				if (fromJson.getStatus() != 200 && StringUtils.isNotBlank(device.getDeviceCode())) {
					throw new RuntimeException("设备:" + device.getDeviceCode() + " 信息注册失败 " + fromJson.getErrorMsg());
				}
			} else {
				if (fromJson.getCode() != 0 && StringUtils.isNotBlank(device.getDeviceNo())) {
					throw new RuntimeException("设备:" + device.getDeviceNo() + " 信息注册失败 " + fromJson.getErrorMsg());
				}
			}

		} catch (IOException e) {
			logger.error("DeviceInfoPostUtil url:{} ,error:{}", url, e.getMessage());
		}catch (Exception e){
			throw new RuntimeException(String.format("设备:" + device.getDeviceCode() + " 信息注册失败 %s", e.getMessage()));
		}
		return responseStr;
	}

	public static String handleData3(String key, String data, String url) {

		String nonce = nonceGen();
		long time = DateUtil.date().getTime();
		data = data.replace("\"raiseDustDTO\":{", "").replace("},", ",");
		String dataStr = String.format("nonce=%s&timestamp=%s&key=%s", nonce, time, key);
		// 获取签名
		String sign = SecureUtil.md5(dataStr);
		String postUrl = url + String.format("?nonce=%s&timestamp=%s&sign=%s", nonce, time, sign);
		String responseStr = "";
		RaiseDustDTO device = new Gson().fromJson(data, RaiseDustDTO.class);
		try {
			logger.info("平台对接，数据接口为："+url+"推送的设备数据为:" + data);
			responseStr = HttpClientUtil.doPost(postUrl, "[" + data + "]");
			logger.info("推送结果为：" + responseStr);

			ResultDTO fromJson = new Gson().fromJson(responseStr, ResultDTO.class);

			if (fromJson.getCode() != 0 && StringUtils.isNotBlank(device.getDeviceNumber())) {
				throw new RuntimeException("设备:" + device.getDeviceNumber() + " 数据推送失败 " + fromJson.getMessage());
			}

		} catch (IOException e) {
			logger.error("DeviceInfoPostUtil url:{} ,error:{}", url, e.getMessage());
		}catch (Exception e){
			throw new RuntimeException(String.format("设备:" + device.getDeviceNumber() + " 数据推送失败 %s", e.getMessage()));
		}
		return responseStr;
	}

	private static String nonceGen() {
		String res = "";
		for (int i = 0; i < 8; i++) {
			res += (int) (Math.random() * 10);
		}
		return res;
	}



}
